﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace GameLogic
{
	public class Barracks : Building
	{
		private const float maxAnimationTimeCounting = 1.5F;
		private const float animationTimeOffset = 0.8F;
		private const float animationSpeed = 0.7F;
		private const int maxUnitsTraining = 5;

		private List<Unit> unitsQueue = new List<Unit>();

		private float elapsedAnimationTime = 0;
		private float elapsedTrainingTime = 0;
		private Position2D dispatchUnitsPosition;

		private bool animationTimeRunning = false;

		public Barracks(GameMain game) : base(game)
		{
			options.Add(new Option( Option.TrainSwordman ));
			options.Add(new Option( Option.TrainPoleAxeMan));
			options.Add(new Option( Option.TrainSwordman ));
		}

		public override void setPosition(Position2D pos)
		{
			base.setPosition(pos);
			dispatchUnitsPosition = new Position2D(pos.X + 150, pos.Y);
		}
		
		public override String getRepresentationState()
		{
			return "Normal";
		}

		public override String getRepresentationURI()
		{
			return "Barracks";
		}

		public override float getTimeElapsed()
		{
			return elapsedAnimationTime;
		}

		public override void update()
		{
			countAnimationTime();

			if (unitsQueue.Count > 0)
			{
				elapsedTrainingTime = elapsedTrainingTime + 0.02F;

				if (unitsQueue[0].getTrainTime() <= elapsedTrainingTime)
				{
					elapsedTrainingTime = 0;

					Unit unit = unitsQueue[0];
					unitsQueue.RemoveAt(0);

					unit.setPosition(dispatchUnitsPosition.clone());
					game.addUnit(unit);
				}
			}
		}

		private void countAnimationTime()
		{
			if (unitsQueue.Count > 0 && unitsQueue[0].getTrainTime() <= animationTimeOffset + elapsedTrainingTime)
				animationTimeRunning = true;

			if (animationTimeRunning) elapsedAnimationTime += 0.02F * animationSpeed;

			if (maxAnimationTimeCounting < elapsedAnimationTime)
			{
				animationTimeRunning = false;
				elapsedAnimationTime = 0;
			}
		}

		public List<Unit> getUnitsQueue()
		{
			return unitsQueue;
		}

		public void train(Unit unit)
		{
			if (maxUnitsTraining > unitsQueue.Count) unitsQueue.Add(unit);
		}
	}
}
